package com.rcloud.server.sealtalk.controller;


import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.controller.base.WxPayBaseController;
import com.rcloud.server.sealtalk.controller.param.PayParam;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.model.dto.PayInfoDto;
import com.rcloud.server.sealtalk.model.response.APIResult;
import com.rcloud.server.sealtalk.model.response.APIResultWrap;
import com.rcloud.server.sealtalk.service.PayService;
import com.rcloud.server.sealtalk.util.IPHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>IJPay 让支付触手可及，封装了微信支付、支付宝支付、银联支付常用的支付方式以及各种常用的接口。</p>
 *
 * <p>不依赖任何第三方 mvc 框架，仅仅作为工具使用简单快速完成支付模块的开发，可轻松嵌入到任何系统里。 </p>
 *
 * <p>IJPay 交流群: 723992875</p>
 *
 * <p>Node.js 版: https://gitee.com/javen205/TNW</p>
 *
 * <p>微信支付 Demo</p>
 *
 * @author Javen
 */
@Slf4j
@RequestMapping("/pay/wxPay")
@RestController
@Api(tags = "微信支付接口")
@AllArgsConstructor
public class WxAppPayController extends WxPayBaseController {

    private final PayService payService;

    /**
     * 微信APP支付
     */
    @PostMapping(value = "/payment")
    @ApiOperation(value = "微信APP支付，根据订单号进行支付", notes = "微信APP支付，根据订单号进行支付")
    public APIResult<Object> payment(@RequestBody PayParam payParam) throws ServiceException {
        //获取支付信息
        PayInfoDto payInfo = payService.pay(payParam);
        //组装支付信息
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .body(payInfo.getBody())
                .attach(payParam.getBusiType().toString())
                .out_trade_no(payInfo.getPayNo())
                .total_fee(payInfo.getPayAmount().multiply(new BigDecimal(100)).intValue() + "")
                .spbill_create_ip(IPHelper.getIpAddr())
                .notify_url(wxPayApiConfig.getDomain().concat("/notice/pay/wx/payNotify"))
                .trade_type(TradeType.APP.getTradeType())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

        String xmlResult = WxPayApi.pushOrder(false, params);
        log.info(xmlResult);
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            throw new ServiceException(ErrorCode.SERVER_ERROR,returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            throw new ServiceException(ErrorCode.SERVER_ERROR,returnMsg);
        }
        // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
        String prepayId = result.get("prepay_id");
        Map<String, String> packageParams = WxPayKit.appPrepayIdCreateSign(wxPayApiConfig.getAppId(), wxPayApiConfig.getMchId(), prepayId,
                wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);
        log.info("返回apk的参数:" + packageParams);
        return APIResultWrap.ok(packageParams);
    }
}
